<?php

namespace App\Console\Commands;

use App\Models\Activity\Activity;
use App\Models\Activity\Category;
use App\Models\Activity\Join;
use App\Models\Common\City;
use App\Models\Common\Country;
use App\Models\Common\File;
use App\Models\Common\Log;
use App\Models\Member\Follow;
use App\Models\Member\FreezeMoneyLog;
use App\Models\Member\Friend;
use App\Models\Member\Member;
use App\Models\Old\Event;
use App\Models\Old\Image;
use App\Models\Old\Region;
use App\Models\Order\Order;
use App\Models\Posts\Posts;
use App\Models\School\School;
use App\Services\Com\ExportService;
use App\Services\Com\PinYinService;
use App\Services\Com\UtilService;

use App\Services\Group\GroupService;
use App\Services\Member\FreezeMoneyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use OSS\OssClient;
use Overtrue\Pinyin\Pinyin;

/**
 *  php artisan test
 */
class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle(){
        self::exportActivity();

    }
    public static function exportActivity(){
        $activities = Activity::where('member_uuid', '4911fc79-1c3c-4776-9993-12ee63c58b21')->pluck('uuid');
        $orders = Join::whereIn('activity_join.activity_uuid', $activities)
            ->join('orders', 'orders.uuid', 'activity_join.order_uuid')
            ->with('activity')->where('orders.rece', '>', 0)->where('orders.state', '!=', 0)->where('orders.state', '!=', -5)
            ->select('orders.*', 'activity_join.code', 'activity_join.activity_uuid')->get();
        $data = [];
        foreach ($orders as $order){
            $data[] = [
                "trade_no"=>$order->trade_no,
                "pay_way"=>$order->pay_way,
                "rece"=>$order->rece,
                "cash"=>$order->cash,
                "code_price"=>$order->code_price,
                "code"=>$order->code,
                "activity_name"=>$order->activity->name,
            ];
        }

        //年龄  性别  留学地域   所在城市  登录次数  发帖数量  资料完善度 是否认证  推荐下载的人
        //设置表头
        $row = [[
            "trade_no"=>'支付订单号',
            "pay_way"=>'支付类型',
            "rece"=>'应付金额',
            "cash"=>'实付金额',
            "code_price"=>'优惠金额',
            "code"=>'优惠码',
            "activity_name"=>'活动名称',
        ]];
        $header = $row;//导出表头
        $excel = new ExportService($data, $header,'用户统计数据15914138232');
        $excel->setColumnWidth(['A' => 20, 'B' => 20, 'C' => 20, 'D' => 20, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 20, 'I' => 20]);
        $excel->setBold(['A1:B1:C1:D1:E1:F1:G1:H1:I1' => true]);

        $path = 'recruit/用户统计数据15914138232_'.date('Y-m-d').'.xlsx';

        Excel::store($excel , $path);
    }


    public function dfMemberImport(){
        $rows = DB::table('yoshop_user')
            ->where('type',1)->where('examine_status',1)->where('user_id', '>', 379)->where('is_delete',0)->get()->toArray();

        foreach ($rows as $key=>$row){
            try {
                $url = 'https://admin.scdeyao.com/store/user/detail?0='.$row->user_id;
                $header[] = 'access-token: 27acce79a2aa447b6676bef9a58412b7';
                $oldUser = UtilService::curl_get($url,$header);
                $license = $oldUser['data']['userInfo']['license'];
                $parentUser = $oldUser['data']['userInfo']['parentUser'];

                $url = 'https://web.scdeyao.com/sys/user/create';
                $data = [
                    'account' => $row->mobile,
                    'phone' => $row->mobile,
                    'real_name' => $row->realname,
                    'avatar' => '',
                    'card_id' => '',
                    'is_promoter' => 0,
                    'nickname' => $row->realname,
                    'pwd' => '123456',
                    'repwd' => '123456',
                    'sex' => '',
                    'status' => 1,
                ];
                $data['customer_store_name'] = $row->store_name;
                $data['customer_name'] = $row->realname;
                $data['customer_mobile'] = $row->mobile;
                $data['customer_company'] = $row->business_name;
                $data['customer_store_type'] = 3;
                $data['customer_company_no'] = $row->tax_number;
                $data['customer_address'] = $row->address;
                $data['customer_state'] = 10;

                $data['customer_area'] = [];

                $province = DB::table('yoshop_region')->where('id', $row->province)->select('name')->get()->toArray();
                if(!empty($province)){
                    $province = $province[0];
                    $cities = DB::table('eb_city_area')->where('name', 'like', "%".trim($province->name, '省')."%")->get()->toArray();
                    if(!empty($cities)){
                        $data['customer_province_id'] = $cities[0]->id;
                        $data['customer_area'][] = $cities[0];
                    }
                }

                $city = DB::table('yoshop_region')->where('id', $row->city)->select('name')->get()->toArray();
                if(!empty($city)){
                    $cities = DB::table('eb_city_area')->where('name', 'like', "%{$city[0]->name}%")->get()->toArray();
                    if(!empty($cities)){
                        $data['customer_city_id'] = $cities[0]->id;
                        $data['customer_area'][] = $cities[0];
                    }
                }

                $area = DB::table('yoshop_region')->where('id', $row->area)->select('name')->get()->toArray();
                if(!empty($area)){
                    $cities = DB::table('eb_city_area')->where('name', 'like', "%{$area[0]->name}%")->get()->toArray();
                    if(!empty($cities)){
                        $data['customer_district_id'] = $cities[0]->id;
                        $data['customer_area'][] = $cities[0];
                    }
                }


                $data['customer_flair'] =[];
                $data['customer_flair'][0]['key'] = '营业执照(营利性门诊或诊所)';
                $customer_flair = [];
                foreach ($license as $li){
                    $customer_flair[] = $li['preview_url'];
                }
                $data['customer_flair'][0]['data'] = $customer_flair;

                if(!empty($parentUser)){
                    $parentUser = DB::table('eb_user')
                        ->where('account',$parentUser['mobile'])->get()->toArray();
                    if(!empty($parentUser)) {
                        $data['spread_time'] = date('Y-m-d H:i:s', $row->create_time);
                        $data['spread_uid'] = $parentUser[0]->uid;
                    }
                }

                $header[] = 'x-token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3ZWIuc2NkZXlhby5jb20iLCJhdWQiOiJ3ZWIuc2NkZXlhby5jb20iLCJpYXQiOjE2ODEyNjE0NzcsIm5iZiI6MTY4MTI2MTQ3NywiZXhwIjoxNjgxMjgzMDc3LCJqdGkiOlsxLCJhZG1pbiJdfQ.L3a2dbk2I13FUfdSuYxuJ9Vg0o4J3VFnUnzTYzKB_zg';
                $user = UtilService::curlPost($url,$data,$header);

            }catch (\Exception $e){
                echo $row->mobile.'/'.$e->getMessage().$e->getLine();
            }
            echo $key."\n";

        }
    }

    public function dfSaleImport(){
        $rows = DB::table('yoshop_user')
            ->whereIn('mobile', [
                '13550741070',
                '13881169685',
                '15281257027',
                '18090172653',
                '17302895921',
                '13541713316',
            ])
            ->where('type',2)->where('is_delete',0)->get()->toArray();

        foreach ($rows as $key=>$row){
            try {
                $url = 'https://web.scdeyao.com/sys/user/create';
                $data = [
                    'account' => $row->mobile,
                    'phone' => $row->mobile,
                    'real_name' => $row->realname,
                    'avatar' => '',
                    'card_id' => '',
                    'is_promoter' => 0,
                    'nickname' => $row->realname,
                    'pwd' => '123456',
                    'repwd' => '123456',
                    'sex' => '',
                    'status' => 1,
                ];
                $header[] = 'x-token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3ZWIuc2NkZXlhby5jb20iLCJhdWQiOiJ3ZWIuc2NkZXlhby5jb20iLCJpYXQiOjE2ODEyNjE0NzcsIm5iZiI6MTY4MTI2MTQ3NywiZXhwIjoxNjgxMjgzMDc3LCJqdGkiOlsxLCJhZG1pbiJdfQ.L3a2dbk2I13FUfdSuYxuJ9Vg0o4J3VFnUnzTYzKB_zg';
                $user = UtilService::curlPost($url,$data,$header);

                $region = $row->region ? json_decode($row->region,true) : [];
                $region_arr = DB::table('yoshop_region')->whereIn('id', $region)->select('name')->get()->toArray();
                $region_arr = array_column($region_arr, 'name');
                foreach ($region_arr as &$re){
                    $re = trim($re, '省');
                }
                $cities = DB::table('eb_city_area')->whereIn('name',$region_arr)->get()->toArray();
                $spread_city = [];
                foreach ($cities as $city){
                    $city_tmp = [];
                    $path = trim($city->path, '/');
                    $path = explode('/', $path);
                    foreach ($path as $p){
                        !empty($p) && $city_tmp[] = $p;
                    }
                    $city_tmp[] = $city->id;
                    $spread_city[] = $city_tmp;
                }

                $url = 'https://web.scdeyao.com/sys/user/setSpread/'.$user['data']['uid'];
                $data = [
                    'is_promoter' => 1,
                    'phone' => $row->mobile,
                    'real_name' => $row->realname,
                    'spread_city' => $spread_city,
                    'spread_name' => '',
                    'user_id' => $user['data']['uid'],
                ];

                $header[] = 'x-token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3ZWIuc2NkZXlhby5jb20iLCJhdWQiOiJ3ZWIuc2NkZXlhby5jb20iLCJpYXQiOjE2ODEyNjE0NzcsIm5iZiI6MTY4MTI2MTQ3NywiZXhwIjoxNjgxMjgzMDc3LCJqdGkiOlsxLCJhZG1pbiJdfQ.L3a2dbk2I13FUfdSuYxuJ9Vg0o4J3VFnUnzTYzKB_zg';
                $user = UtilService::curlPost($url,$data,$header);
            }catch (\Exception $e){
                echo $row->mobile.'/'.$e->getMessage().$e->getLine();
            }
            echo $key."\n";

        }
    }

    public function dfSaleExport(){
        $rows = DB::table('yoshop_user')->select(['realname','mobile','region'])->where('type',2)->where('is_delete',0)->get()->toArray();

        $data = [];
        foreach ($rows as &$row){
            $region = $row->region ? json_decode($row->region,true) : [];

            $region_arr = DB::table('yoshop_region')->whereIn('id', $region)->select('name')->get()->toArray();

            $region_arr = array_column($region_arr, 'name');

            $row->region = $region_arr ? implode(',',$region_arr) : '';
        }
        //设置表头
        $header = [[
            "realname"=>'姓名',
            "mobile"=>'手机号码',
            "region"=>'负责区域',
        ]];
        $excel = new ExportService($rows, $header,'业务员统计数据');
        $excel->setColumnWidth(['A' => 20, 'B' => 20, 'C' => 20]);
        $excel->setBold(['A1:B1:C1' => true]);

        DB::commit();
        $path = 'recruit/业务员统计数据_'.date('Y-m-d').'.xlsx';

        Excel::store($excel , $path);
    }

    public function memberData(){
        $rows = Member::where('mobile', 'not like', '112%')->with('country')->with('inviter')->with('city')->with('subjects')->with('works')->get();

        $data = [];
        foreach ($rows as $k=>$row){
            echo $k."\n";
            $i = 0;
            if($row->avatar_url) ++$i;
            if($row->country_uuid) ++$i;
            if($row->birthday) ++$i;
            if($row->sex) ++$i;
            if($row->city_id) ++$i;
            if($row->subjects) ++$i;
            if($row->works) ++$i;

            $login_num = Log::where('member_uuid', $row->uuid)->where('url', 'api/client/auth/login_mobile_captcha')->count('*');
            $post_num = Posts::where('member_uuid', $row->uuid)->count('*');
            $recommend = Member::where('inviter_uuid', $row->uuid)->count('*');
            $data[] = [
                "birthday"=>$row->birthday,
                "age"=>$row->birthday ? UtilService::getAge(strtotime($row->birthday)) : '无',
                "sex"=>Member::$sexArr[$row->sex],
                "study_country"=>$row->country ? $row->country->name : '无',
                "city"=>$row->city ? $row->city->name : '无',
                "login_num"=> empty($login_num) ? 1 : $login_num,
                "post_num"=> empty($post_num) ? 0 : $post_num,
                "info_point"=>bcdiv($i * 100, 7, 0) .'%',
                "is_auth"=>$row->state == 200 ? '是' : '否',
                "recommend"=>empty($recommend) ? 0 : $recommend,
            ];
        }

        //年龄  性别  留学地域   所在城市  登录次数  发帖数量  资料完善度 是否认证  推荐下载的人
        //设置表头
        $row = [[
            "birthday"=>'生日',
            "age"=>'年龄',
            "sex"=>'性别',
            "study_country"=>'留学地域',
            "city"=>'所在城市',
            "login_num"=>'登录次数',
            "post_num"=>'发帖数量',
            "info_point"=>'资料完善度',
            "is_auth"=>'是否认证',
            "recommend"=>'推荐下载的人',
        ]];
        $header = $row;//导出表头
        $excel = new ExportService($data, $header,'用户统计数据');
        $excel->setColumnWidth(['A' => 20, 'B' => 20, 'C' => 20, 'D' => 20, 'E' => 20, 'F' => 20, 'G' => 20, 'H' => 20, 'I' => 20]);
        $excel->setBold(['A1:B1:C1:D1:E1:F1:G1:H1:I1' => true]);

        DB::commit();
        $path = 'recruit/用户统计数据_'.date('Y-m-d').'.xlsx';

        Excel::store($excel , $path);
    }
    //update members set money=0,freeze_money=0,total_money=0;

    //update activity set state=15 where state=20;
    public function activityUpdate(){

        //增加活动举办方（用户）冻结金
        $joinOrders = Join::where('state', '!=', 0)->where('rece', '>', 0)->with('member')->with('order')->with('activity')->get();
        foreach ($joinOrders as $key=>$joinOrder){
            echo $key."\n";

            $freezeMoney = bcmul($joinOrder->rece, 1, 2);

            if($freezeMoney > 0){
                FreezeMoneyService::income([$joinOrder->order->id], $joinOrder->activity->member_uuid, $freezeMoney, 3, '活动报名收入-'.$joinOrder->activity->name,
                    $member->avatar_url ?? '', $joinOrder->activity_uuid);
            }

        }

    }


    public static function randip(){
        $ip_1 = -1;
        $ip_2 = -1;
        $ip_3 = rand(0,255);
        $ip_4 = rand(0,255);
        $ipall = array(
            array(array(58,14),array(58,25)),
            array(array(58,30),array(58,63)),
            array(array(58,66),array(58,67)),
            array(array(60,200),array(60,204)),
            array(array(60,160),array(60,191)),
            array(array(60,208),array(60,223)),
            array(array(117,48),array(117,51)),
            array(array(117,57),array(117,57)),
            array(array(121,8),array(121,29)),
            array(array(121,192),array(121,199)),
            array(array(123,144),array(123,149)),
            array(array(124,112),array(124,119)),
            array(array(125,64),array(125,98)),
            array(array(222,128),array(222,143)),
            array(array(222,160),array(222,163)),
            array(array(220,248),array(220,252)),
            array(array(211,163),array(211,163)),
            array(array(210,21),array(210,22)),
            array(array(125,32),array(125,47))
        );
        $ip_p = rand(0,count($ipall)-1);#随机生成需要IP段
        $ip_1 = $ipall[$ip_p][0][0];
        if($ipall[$ip_p][0][1] == $ipall[$ip_p][1][1]){
            $ip_2 = $ipall[$ip_p][0][1];
        }else{
            $ip_2 = rand(intval($ipall[$ip_p][0][1]),intval($ipall[$ip_p][1][1]));
        }
        $member = null;
        $ipall  = null;
        return $ip_1.'.'.$ip_2.'.'.$ip_3.'.'.$ip_4;

    }

    public static $addr = [[[[[["中正区","710101"],["大同区","710102"],["中山区","710103"],["松山区","710104"],["大安区","710105"],["万华区","710106"],["信义区","710107"],["士林区","710108"],["北投区","710109"],["内湖区","710110"],["南港区","710111"],["文山区","710112"],["其它区","710113"]],"台北市","710100"],[[["新兴区","710201"],["前金区","710202"],["芩雅区","710203"],["盐埕区","710204"],["鼓山区","710205"],["旗津区","710206"],["前镇区","710207"],["三民区","710208"],["左营区","710209"],["楠梓区","710210"],["小港区","710211"],["其它区","710212"]],"高雄市","710200"],[[["中西区","710301"],["东区","710302"],["南区","710303"],["北区","710304"],["安平区","710305"],["安南区","710306"],["其它区","710307"]],"台南市","710300"],[[["中区","710401"],["东区","710402"],["南区","710403"],["西区","710404"],["北区","710405"],["北屯区","710406"],["西屯区","710407"],["南屯区","710408"],["其它区","710409"]],"台中市","710400"],["金门县","710500"],["南投县","710600"],[[["仁爱区","710701"],["信义区","710702"],["中正区","710703"],["中山区","710704"],["安乐区","710705"],["暖暖区","710706"],["七堵区","710707"],["其它区","710708"]],"基隆市","710700"],[[["东区","710801"],["北区","710802"],["香山区","710803"],["其它区","710804"]],"新竹市","710800"],[[["东区","710901"],["西区","710902"],["其它区","710903"]],"嘉义市","710900"],["新北市","711100"],["宜兰县","711200"],["新竹县","711300"],["桃园县","711400"],["苗栗县","711500"],["彰化县","711700"],["嘉义县","711900"],["云林县","712100"],["屏东县","712400"],["台东县","712500"],["花莲县","712600"],["澎湖县","712700"]],"台湾","710000"],[[[[["中西区","810101"],["湾仔","810102"],["东区","810103"],["南区","810104"]],"香港岛","810100"],[[["九龙城区","810201"],["油尖旺区","810202"],["深水埗区","810203"],["黄大仙区","810204"],["观塘区","810205"]],"九龙","810200"],[[["北区","810301"],["大埔区","810302"],["沙田区","810303"],["西贡区","810304"],["元朗区","810305"],["屯门区","810306"],["荃湾区","810307"],["葵青区","810308"],["离岛区","810309"]],"新界","810300"]],"香港特别行政区","810000"],[[[[["大堂区","820100"],["风顺堂区","820100"],["花地玛堂区","820100"],["花王堂区","820100"],["望德堂区","820100"],["其他区","820100"]],"澳门半岛","820100"],[[["嘉模堂区","820200"],["路凼填海区","820200"],["圣方济各堂区","820200"],["其他区","820200"]],"离岛","820200"]],"澳门特别行政区","820000"]];
    public static function getCode($name){
        $addrs = self::$addr;
        foreach ($addrs as $addr){
            if($addr[1] == $name) return $addr[2];
        }
    }

    public function syncCity(){
        $citys = \App\Models\Old\City::where('level', 0)->where('area_code', '=', 0)->get()->toArray();
//        $citys = \App\Models\Old\City::where('area_code', '!=', '')->get()->toArray();

        $pinyin = new Pinyin();

        foreach ($citys as $key=>$city){
            try {
//                if(!$city['area_code']) continue;
                $py = $pinyin->convert($city['name']);
                $id =  substr($city['area_code'], 0 ,6);




                if(!$id){
                    $id = self::getCode($city['name']);
                }

                $hasCity = City::find($id);
                var_dump($id);
                if($hasCity) continue;

                if(!$id) continue;

                $parent = $city['parent_id'] ? \App\Models\Old\City::where('city_id', $city['parent_id'])->first() : '';
                $parent_id = $parent ? $parent->area_code : 0;
                $parent_id = substr($parent_id, 0, 6);

                $newParent = City::find($parent_id);
                City::create([
                    'id' =>$id,
                    'parent_id' => $parent_id,
                    'path_names' => $city['merger_name'],
                    'paths' => !empty($newParent) && !empty($newParent->paths) ? $newParent->paths .':'. $id : $id,
                    'name' => $city['name'],
                    'level' => $city['level'],
                    'is_city' => $city['level'] == 1 ? 1 : 0,
                    'lng' => $city['lng'],
                    'lat' => $city['lat'],
                    'initial' => strtoupper($py[0][0]),
                ]);
            }catch (\Exception $e){
                dd($city, $e);
            }
            echo $key."\n";


        }
    }

    public function handle12321321(){
        $rows = Member::where('mobile', '!=', config('sms.migo_phone'))->get();
        //和migo账号默认是好友关系  11200000800
        $migoMember = Member::where('mobile', config('sms.migo_phone'))->first();
        foreach ($rows as $key=>$member){
            try {
                echo $key."\n";

                if($migoMember){
                    $follow = Follow::where('followed_member_uuid', $migoMember->uuid)->where('member_uuid', $member->uuid)->first();
                    if(!$follow){
                        Follow::create([
                            'followed_member_uuid' => $migoMember->uuid,
                            'member_uuid' => $member->uuid,
                        ]);
                    }
                    $follow = Follow::where('followed_member_uuid', $member->uuid)->where('member_uuid', $migoMember->uuid)->first();
                    if(!$follow){
                        Follow::create([
                            'followed_member_uuid' => $member->uuid,
                            'member_uuid' => $migoMember->uuid,
                        ]);
                    }

                    $follow = Friend::where('member_uuid', $migoMember->uuid)->where('friend_member_uuid', $member->uuid)->first();
                    if(!$follow){
                        Friend::create([
                            'member_uuid' => $migoMember->uuid,
                            'friend_member_uuid' => $member->uuid,
                        ]);
                    }
                    $follow = Friend::where('member_uuid', $member->uuid)->where('friend_member_uuid', $migoMember->uuid)->first();
                    if(!$follow){
                        Friend::create([
                            'member_uuid' => $member->uuid,
                            'friend_member_uuid' => $migoMember->uuid,
                        ]);
                    }
                }

            }catch (\Exception $e){

            }

        }
    }

    public function schoolIni(){
        $rows = School::get();
        foreach ($rows as $key=>$row){
            echo $key."\n";
            try {
                $pinyin = new Pinyin();
                $py = $pinyin->convert($row->cn_name);

                $row->update([
                    'initial' => strtoupper($py[0][0])
                ]);
            }catch (\Exception $e){

            }

        }
    }
    public function handle111(){
//        $str = '55839,55840,55841,55842,55843,55844,55845,55846,55901';
//        $albums = explode(',', $str);
//
//        $imageArr = Image::whereIn('image_id', $albums)->get()->toArray();
//        dd(!empty($imageArr));


        $rows = Event::with('eventType')->whereIn('uid', [1, 15843,  52202,  55701,
            66879,  42829,  53108,  52584,  38555 ,  69199,  15086,
            ])->where('status', 1)->get();
        foreach ($rows as $key=>$row){
            echo $key.'_'.$row['event_id']."\n";
            try {
                DB::beginTransaction();

                $old = Activity::where('is_old', $row['event_id'])->first();
                if($old) continue;

                $param['city_id'] = 0;
                $param['province_id'] = 0;
                $param['area_id'] = 0;
                if($row['city']){
                    $city =  Region::where('region_id', $row['city'])->first();
                    $param['city_id'] =   $city ? $city->adcode : 0;
                }

                if($param['city_id'] && $city = City::find($param['city_id'])){
                    $paths = explode(':', $city->paths);
                    $param['province_id'] = $paths[0];
                    $param['city_id'] = isset($paths[1]) ? $paths[1] : 0;
                    $param['area_id'] = isset($paths[2]) ? $paths[2] : 0;
                }

                $data['name'] = $row['title'];
                $data['head_img'] = 'https://api.imhaiguiapp.com'.$row['cover'];
                $data['city'] = $param['city_id'];
                $data['province_id'] = $param['province_id'];
                $data['area_id'] = $param['area_id'];
                $data['address'] = $row['address'];
                $data['content'] = $row['content'];
                $data['type'] = $row['address'] ? 2 : 1;
                $data['member_uuid'] = '6bc405f0-2b04-42a6-8e3e-0c7620152d7b';
                $data['address_short'] = $row['specific_address'];
                $data['longitude'] = $row['longitude'];
                $data['latitude'] = $row['latitude'];
                $data['start_time'] = date('Y-m-d H:i:s', $row['stime']);
                $data['end_time'] = date('Y-m-d H:i:s', $row['etime']);
                $data['stock'] = $row['people'];
                $data['is_old'] = $row['event_id'];
                $data['state'] = 15;

                if($row->eventType){
                    $category = Category::where('name', $row->eventType->name)->first();
                    if(!$category){
                        $category = Category::create([
                            'name'=> $row->eventType->name,
                            'state'=> 1,
                        ]);
                    }

                    $data['category_uuid'] = $category->uuid;
                }

                $result = Activity::create($data);

                $cover_file = file_get_contents('https://api.imhaiguiapp.com'.$row['cover']);
                $filename = $result->uuid.'.jpg';
                Storage::disk()->put('tmp/'.$filename, $cover_file);

                $imageArr = [];
                if($row['album']){
                    $albums = explode(',', $row['album']);
                    $imageArr = Image::whereIn('image_id', $albums)->get()->toArray();
                }

                // 处理附件  55839,55840,55841,55842,55843,55844,55845,55846,55901
                if (isset($imageArr) && !empty($imageArr)) {
                    echo $row['event_id'].'有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片有图片\n';
                    // 批量写入
                    foreach ($imageArr as $ii => $file) {
                        $uuid = UtilService::uniqid();
                        $obj = file_get_contents('https://api.imhaiguiapp.com'.$file['filepath']);
                        $path = UtilService::ossUploadObject('activity/'.date('Ymd').'/'.$uuid.'.jpg', $obj);
                        File::create([
                            'service_id' => $result->uuid,
                            'place' => 'list',
                            'path' => $path,
                            'type' => 1,
                            'size' => $file['filesize'] ?? '',
                            'height' => $file['height'] ?? '',
                            'width' => $file['width'] ?? '',
                            'sort' => 0,
                        ]);

                        echo $ii."张图片 \n";
                    }
                }

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                echo 'fail:'.$e->getMessage().$e->getLine()."\n";
            }


            echo 'success'."\n";

        }
    }


    public static function scan_dir($dir) {
        if ($handle = opendir($dir)) {
            while (false !== ($file = readdir($handle))) {
                if($file=='..' || $file=='.') continue;

                if(is_file($dir.'/'.$file)) {
                    $file_list[] = $dir.'/'.$file;
                    continue;
                }

                $file_list[$file] = self::scan_dir($dir.'/'.$file);
                foreach($file_list[$file] as $infile) {
                    $file_list[] = $infile;
                }
                unset($file_list[$file]);
            }
            closedir($handle);

            return $file_list;
        }
    }

    public function saveActivityImg(){
        $ossClient = new OssClient(config('aliyun.aliyunoss.accessKeyId'), config('aliyun.aliyunoss.accessKeySecret'), config('aliyun.aliyunoss.endpoint'));

        $files = self::scan_dir('D:\data\api\public\uploadfiles\activity');
        foreach ($files as $key=>$file){
            try {
                echo $key."\n";
                $uuid = basename($file, '.jpg');

                $response = $ossClient->uploadFile(config('aliyun.aliyunoss.bucket'), 'activity/'.$uuid.'.jpg', $file);

                $activity = Activity::where('uuid', $uuid)->first();

                if($activity){
                    $activity->update([
                        'head_img'=>$response['oss-request-url']
                    ]);
                }
            }catch (\Exception $e){

            }

        }
    }

    public function saveCountry(){
        $ossClient = new OssClient(config('aliyun.aliyunoss.accessKeyId'), config('aliyun.aliyunoss.accessKeySecret'), config('aliyun.aliyunoss.endpoint'));

        $files = self::scan_dir('D:\data\api\public\uploadfiles\country');
        foreach ($files as $key=>$file){
            echo $key."\n";
            $uuid = basename($file, '.png');

            $response = $ossClient->uploadFile(config('aliyun.aliyunoss.bucket'), 'country/'.$uuid.'.png', $file);

            $country = Country::where('uuid', $uuid)->first();

            $country->update([
                'nationalflag'=>$response['oss-request-url']
            ]);
        }
    }

    public function saveImg(){
        $rows = Country::get();
        foreach ($rows as $key=>$row){
            echo $key."\n";
            if(empty($row->nationalflag)) continue;
            $file = file_get_contents($row->nationalflag);

            $filename = $row->uuid.'.jpg';
            $result = Storage::disk()->put('tmp/'.$filename, $file);
            echo $result."\n";
        }

    }

    public function country(){

        $rows = DB::connection('old_migo')->table('imhg_country')->get();
        foreach ($rows as $key=>$row){
            echo $key."\n";
            $new = DB::connection('mysql')->table('com_country1')->where('name', $row->name)->first();

            $data = [
                'id' => $row->country_id,
                'name' => $row->name,
                'mobile_prefix' => !empty($row->mobile_prefix) ? $row->mobile_prefix : trim($new->areacode, '+'),
                'area' => $row->area,
                'initial' => !empty($row->initial) ? $row->initial[0] : '',
                'nationalflag' => !empty($new->nationalflag) ? $new->nationalflag : '',
                'code' => !empty($new->code) ? $new->code : '',
            ];

            Country::create($data);
        }
    }

    public function school(){

        $rows = DB::connection('old_migo')->table('imhg_school')->get();
        foreach ($rows as $key=>$row){
            echo $key."\n";
            $new = DB::connection('mysql')->table('com_country')->where('id', $row->country_id)->first();

            $data = [
                'name' => $row->name,
                'cn_name' => $row->cn_name,
                'country_uuid' => $new->uuid,
                'initial' => $row->initial,
                'state' => 2,
            ];

            School::create($data);
        }
    }

    public function countrytest(){
        $url = 'https://api.jisuapi.com/country/query?name=&continent=&language=&iscountry=0&appkey=e3153f1a7c7fd8ad ';

        $data = UtilService::curlPost($url)['result'];

        foreach ($data as $key=>$country){
            echo $key."\n";
            Country::create($country);
        }
    }




}
